package com.tbit.uqbike.client.handler.borrowbikehandler;

import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigLogDao;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfigLog;
import com.tbit.uqbike.client.service.UserService;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lh2
 * @ClassName: MoneyCheckHandler
 * @Description: 用户余额校验处理器
 * @date 2023-07-26 03:40:07
 */
@Slf4j
@Component
public class MoneyCheckHandler extends AbstractCheckHandler {
    @Autowired
    private UserService userService;
    @Autowired
    private BorrowCheckConfigLogDao borrowCheckConfigLogMapper;

    @Override
    public ResultMsg handle(BorrowBikeVO vo, String serialNO) {
        log.info("【用户余额校验处理器】校验开始...");
        // 降级：如果配置了降级，则跳过此处理器，执行下一个处理器
        if (super.getConfig().getDown() == 1) {
            log.info("【用户余额校验处理器】被降级，已自动跳过！");
            return super.next(vo, serialNO);
        }

        User user = vo.getUser();
        /** 金额判断 */
        User userdb = userService.getByUserId(user.getUserId());
        if (userdb.getMoney() - userdb.getRideMoney() < 0) {
            return ResultMsg.fail(-3039, "您的账户已经欠费，请补交欠费金额", TraceUtil.getTraceIdByLocal());
        }
        log.info("【用户余额校验处理器】校验通过！");
        BorrowCheckConfigLog bccLog = new BorrowCheckConfigLog();
        bccLog.setSerialNO(serialNO);
        bccLog.setAccountId(vo.getUser().getAccountId());
        bccLog.setUserId(vo.getUser().getUserId());
        bccLog.setHandlerName(this.getConfig().getHandlerName());
        bccLog.setOrderNum(this.getConfig().getOrderNum());
        bccLog.setExecuteResult(1);
        borrowCheckConfigLogMapper.insertSelective(bccLog);
        // 执行下一个处理器
        return super.next(vo, serialNO);
    }
}
